<template>
  <div>
    <t-popconfirm :visible="visible" placement="top-left" @confirm="onConfirm" @visible-change="onVisibleChange">
      <template #icon><p></p></template>
      <template #content>
        <div style="width: 360px">
          <t-form :data="formData" :rules="rules" ref="Form" layout="inline" label-align="top" @submit="onBatchSubmit">
            <t-form-item name="codes" style="flex: 1;margin-right: 18px;">
              <template #label>
                <p class="form-label2">批量录入SN码</p>
              </template>
              <t-textarea v-model="formData.codes" :autosize="{ minRows: 3, maxRows: 5 }" placeholder="请输入SN，多个请换行"></t-textarea>
            </t-form-item>
          </t-form>
        </div>
      </template>
      <t-link class="edit-btn-color ml8" hover="color">批量录入</t-link>
    </t-popconfirm>
  </div>
</template>

<script>
export default {
  name: 'BatchSn',
  data() {
    return {
      visible: false,
      formData: {
        codes: ''
      },
      rules: {
        codes: [{ required: true, message: '请输入SN码', trigger: 'blur' }],
      },
    }
  },
  methods: {
    onConfirm() {
      this.$refs.Form.submit();
    },
    onBatchSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        // 对codes进行处理,按照逗号或换行符进行分割
        const codes = this.formData.codes.split(/,|\n/).filter(item=> item)
        // 对 codes 数组进行去重
        const arr = codes.reduce((acc, cur) => {
          if (!acc.includes(cur)) {
            acc.push(cur);
          }
          return acc;
        }, []);

        this.visible = false
        this.formData.codes = ''
        this.$emit('change', arr)
        //const snDataList = codes.map((item, index)=> ({
        //  sn: item,
          //title: this.row.title,
          //product_id: this.productId, // 产品ID
          //unit_id: this.row.unit_id,  // 单位ID
          //unit_title: this.row.unit_title || '',  // 单位ID
          //quantity: 1, // 数量
          //is_sn: 1, // 开启SN序列号（0关闭；1开启）
          //unit_price: '', // 含税单价（进货价）
          //remark: '', // 备注（50个字内）
        //}))


        //console.log('snDataList', snDataList)
        //this.formData.snDataList = [...this.formData.snDataList, ...snDataList]
        //// 按照SN码为参照进行去重处理
        //this.formData.snDataList = this.formData.snDataList.reduce((acc, cur) => {
        //  const hasDuplicate = acc.some(item => item.sn === cur.sn);
        //  if (!hasDuplicate) {
        //    acc.push(cur);
        //  }
        //  return acc;
        //}, []);

        //this.visible = false
        //this.formData.codes = ''
      } else {
        this.$message.error(firstError);
      }
    },
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.visible = val;
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
